import { _decorator, Component, Node, input, Input, EventTouch, Vec2, EventKeyboard, KeyCode, log } from 'cc';
import { GridMapManager } from './GridMapManager';
const { ccclass, property } = _decorator;

@ccclass('GridEditor')
export class GridEditor extends Component {
    @property(GridMapManager)
    gridMapManager: GridMapManager = null;

    @property
    isEditing: boolean = false; // 是否处于编辑模式

    start() {
        // 注册触摸和键盘事件
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onDestroy() {
        // 取消注册事件
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onKeyDown(event: EventKeyboard) {
        // 按E键切换编辑模式
        if (event.keyCode === KeyCode.KEY_E) {
            this.isEditing = !this.isEditing;
            console.log(this.isEditing ? "进入编辑模式" : "退出编辑模式");
        }
    }

    onTouchStart(event: EventTouch) {
        // 只有在编辑模式下才处理点击
        if (!this.isEditing) return;

        // 获取点击位置
        const touchPos = event.getUILocation();
        // 转换为世界坐标
        const worldPos = new Vec2(touchPos.x, touchPos.y);
        // 转换为网格坐标
        const gridPos = this.gridMapManager.worldToGrid(worldPos);

        // 检查坐标是否有效并打印日志
        if (this.gridMapManager.isValidPosition(gridPos.x, gridPos.y)) {
            this.gridMapManager.toggleWalkable(gridPos.x, gridPos.y);
            // 输出调试信息
            const node = this.gridMapManager.getNodeAt(gridPos.x, gridPos.y);
            log(`Toggle grid at (${gridPos.x}, ${gridPos.y}), walkable: ${node.walkable}`);
        }
    }
}